﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StackExchange.Redis;

namespace Redis读写分离.Common
{
    // 轮询选择策略
    public class RoundRobinSelectionStrategy : IReadServerSelectionStrategy
    {
        private int _currentIndex = 0;
        private readonly object _lock = new object();

        public IDatabase SelectReadDatabase(IList<ConnectionMultiplexer> readConnections, int db = -1)
        {
            if (readConnections.Count == 0) return null;

            lock (_lock)
            {
                var Db = readConnections[_currentIndex].GetDatabase(db);
                _currentIndex = (_currentIndex + 1) % readConnections.Count;
                return Db;
            }
        }
    }
}
